package com.cp.order.platform.web;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cp.order.model.Goods;
import com.cp.order.model.GoodsBrand;
import com.cp.order.model.GoodsMatching;
import com.cp.order.model.GoodsStore;
import com.cp.order.model.GoodsType;
import com.cp.order.model.StoreHouse;
import com.cp.order.platform.BaseController;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;

public class GoodsController extends BaseController {

	public void index() {
		setAttr("brand", JsonKit.toJson(GoodsBrand.dao.search()));
		setAttr("type", JsonKit.toJson(GoodsType.dao.search()));
		setAttr("store", JsonKit.toJson(StoreHouse.dao.search()));
		renderFreeMarker("goods.html");
	}

	public void addGoods() {
		setAttr("brand", JsonKit.toJson(GoodsBrand.dao.search()));
		setAttr("type", JsonKit.toJson(GoodsType.dao.search()));
		setAttr("store", JsonKit.toJson(StoreHouse.dao.search()));
		renderFreeMarker("goodsAdd.html");
	}

	public void editGoods() {
		setAttr("brand", JsonKit.toJson(GoodsBrand.dao.search()));
		setAttr("type", JsonKit.toJson(GoodsType.dao.search()));
		setAttr("store", JsonKit.toJson(StoreHouse.dao.search()));
		renderFreeMarker("goodsEdit.html");
	}

	public void selectGoods() {
		setAttr("brand", JsonKit.toJson(GoodsBrand.dao.search()));
		setAttr("type", JsonKit.toJson(GoodsType.dao.search()));
		renderFreeMarker("selectGoods.html");
	}

	/**
	 * 修改库存
	 */
	public void editGoodsStore() {
		setAttr("store", JsonKit.toJson(StoreHouse.dao.search()));
		renderFreeMarker("goodsStoreEdit.html");
	}

	public void list() {
		int cpage = getParaToInt("cpage", 1);
		int pageSize = getParaToInt("pagesize", 10);

		HashMap<String, String> params = new HashMap<>();
		params.put("goods_spec", getPara("goods_spec"));
		params.put("goods_brand", getPara("goods_brand"));
		params.put("goods_type", getPara("goods_type"));
		params.put("status", getPara("status"));

		Page<Goods> result = Goods.dao.queryList(params, cpage, pageSize);

		if (result.getTotalRow() == 0) {
			returnOK(result);
			return;
		}
		String ids = "";
		for (int i = 0; i < result.getList().size(); i++) {
			ids += result.getList().get(i).getId() + ",";
		}
		if (ids.length() > 0) {
			ids = ids.substring(0, ids.length() - 1);
		}
		List<GoodsStore> goodsStores = GoodsStore.dao.search(ids);

		for (Goods goods : result.getList()) {
			for (int i = 0; i < goodsStores.size(); i++) {
				if (goods.getId().equals(goodsStores.get(i).getGoodsId())) {
					if (goods.get("goodsStores") == null) {
						goods.put("goodsStores", new ArrayList<GoodsStore>());
					}

					ArrayList<GoodsStore> list = goods.get("goodsStores");
					list.add(goodsStores.get(i));
				}
			}
		}

		returnOK(result);
	}

	public void ptList() {
		int goodsId = getParaToInt("goodsId", 1);
		returnOK(GoodsMatching.dao.searchPt(goodsId));
	}

	public void warringList() {
		int cpage = getParaToInt("cpage", 1);
		int pageSize = getParaToInt("pagesize", 10);

		HashMap<String, String> params = new HashMap<>();
		params.put("goods_spec", getPara("goods_spec"));
		params.put("goods_brand", getPara("goods_brand"));
		params.put("goods_type", getPara("goods_type"));

		Page<Goods> result = Goods.dao.queryWarringList(params, cpage, pageSize);

		if (result.getTotalRow() == 0) {
			returnOK(result);
			return;
		}
		String ids = "";
		for (int i = 0; i < result.getList().size(); i++) {
			ids += result.getList().get(i).getId() + ",";
		}
		if (ids.length() > 0) {
			ids = ids.substring(0, ids.length() - 1);
		}
		List<GoodsStore> goodsStores = GoodsStore.dao.search(ids);

		for (Goods goods : result.getList()) {
			for (int i = 0; i < goodsStores.size(); i++) {
				if (goods.getId().equals(goodsStores.get(i).getGoodsId())) {
					if (goods.get("goodsStores") == null) {
						goods.put("goodsStores", new ArrayList<GoodsStore>());
					}

					ArrayList<GoodsStore> list = goods.get("goodsStores");
					list.add(goodsStores.get(i));
				}
			}
		}

		returnOK(result);
	}

	public void add() {
		Goods goods = getModel(Goods.class, "goods");
		goods.setStatus(0);
		boolean flag = Db.tx(new IAtom() {

			@Override
			public boolean run() throws SQLException {
				boolean flag = true;
				JSONObject jsonObject = JSON.parseObject(getPara("goodsStore"));
				int autoId = Goods.dao.getAutoIncrement();
				for (Entry<String, Object> entry : jsonObject.entrySet()) {
					GoodsStore goodsStore = new GoodsStore();
					goodsStore.setLastTime(new Date());
					goodsStore.setGoodsId(autoId);
					goodsStore.setStoreId(Integer.parseInt(entry.getKey()));
					goodsStore.setNum(Integer.parseInt(entry.getValue().toString()));
					flag = goodsStore.save();
				}
				JSONObject ptJsonObject = JSON.parseObject(getPara("pt"));
				for (Entry<String, Object> entry : ptJsonObject.entrySet()) {
					GoodsMatching goodsMatching = new GoodsMatching();
					goodsMatching.setGoodsId(autoId);
					goodsMatching.setGoodsMatchingId(Integer.valueOf(entry.getKey()));
					goodsMatching.setDefaultNum(Integer.valueOf(entry.getValue().toString()));
					flag = goodsMatching.save();
				}
				return goods.save() && flag;
			}
		});
		if (flag) {
			returnOK();
		} else {
			returnBusinessError("添加失败");
		}
	}

	public void update() {
		Goods goods = getModel(Goods.class, "goods");
		goods.setStatus(0);
		boolean flag = Db.tx(new IAtom() {

			@Override
			public boolean run() throws SQLException {
				boolean flag = GoodsStore.dao.deleteByGoodsId(goods.getId());
				flag = GoodsMatching.dao.deleteByGoodsId(goods.getId());
				JSONObject jsonObject = JSON.parseObject(getPara("goodsStore"));
				for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
					GoodsStore goodsStore = new GoodsStore();
					goodsStore.setLastTime(new Date());
					goodsStore.setGoodsId(goods.getId());
					goodsStore.setStoreId(Integer.parseInt(entry.getKey()));
					goodsStore.setNum(Integer.parseInt(entry.getValue().toString()));
					flag = goodsStore.save();
				}
				JSONObject ptJsonObject = JSON.parseObject(getPara("pt"));
				for (Entry<String, Object> entry : ptJsonObject.entrySet()) {
					GoodsMatching goodsMatching = new GoodsMatching();
					goodsMatching.setGoodsId(goods.getId());
					goodsMatching.setGoodsMatchingId(Integer.valueOf(entry.getKey()));
					goodsMatching.setDefaultNum(Integer.valueOf(entry.getValue().toString()));
					flag = goodsMatching.save();
				}
				return goods.update() && flag;
			}
		});
		if (flag) {
			returnOK();
		} else {
			returnBusinessError("修改失败");
		}
	}

	/**
	 * 恢复弃用
	 */
	public void recovery() {
		int id = getParaToInt("id");
		Goods goods = new Goods();
		goods.setId(id);
		goods.setStatus(0);
		if (goods.update()) {
			returnOK();
		} else {
			returnBusinessError("恢复失败");
		}
	}

	public void delete() {
		int id = getParaToInt("id");
		Goods goods = new Goods();
		goods.setId(id);
		goods.setStatus(1);// 逻辑删除
		if (goods.update()) {
			returnOK();
		} else {
			returnBusinessError("删除失败");
		}
	}

}
